/*global pi */
pi.mod.define('pi.string', function (pi) {
	"use strict";
	var indexFormatString, module = {},
		dllPath = "TestDll.dll";

	//调用c的字符串格式化
	indexFormatString = 0;
	module.format = function () {
		var i, s, arr, len;
		if (!indexFormatString) {
			indexFormatString = pi.vcall.register(dllPath, "FormatString", pi.vcall.TYPE_STRING, [pi.vcall.TYPE_STRING, pi.vcall.TYPE_VA]);
		}
		//Array.concat(arguments)不行, arguments不是Array实例
		len = arguments.length + 1;
		arr = pi.lang.createArray(len);
		arr[0] = indexFormatString;
		for (i = 0; i < len - 1; i += 1) {
			arr[i + 1] = arguments[i];
		}
		//see apply usage
		s = pi.vcall.invoke.apply(null, arr); //null赋值给this
		return s;
	};

	//调用c的字符串格式化(先将参数全部转换为string,适用于变量含undefined的情形)
	module.formatAuto = function () {
		var i, s, len, arr;
		if (!indexFormatString) {
			indexFormatString = pi.vcall.register(dllPath, "FormatString", pi.vcall.TYPE_STRING, [pi.vcall.TYPE_STRING, pi.vcall.TYPE_VA]);
		}

		len = arguments.length + 1;
		arr = pi.lang.createArray(len);
		arr[0] = indexFormatString;
		for (i = 0; i < len - 1; i += 1) {
			arr[i + 1] = String(arguments[i]); //仅这里不同
		}
		//see apply usage
		s = pi.vcall.invoke.apply(null, arr); //null赋值给this
		return s;
	};

	//将|str|用指定|val|填充到|width|宽度
	//[val, 0]: 长度为1的填充字符
	module.padLeft = function (str, width, val) {
		var i;
		val = pi.util.DV(val, 0);
		for (i = str.length; i < width; i += 1) {
			str = val + str;
		}
		return str;
	};

	//trim begin & end
	module.trim = function (str) {
		return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	};

	/* pi.string.StringBuffer */
	module.StringBuffer = function () {
		this.strings = [];
	};

	module.StringBuffer.prototype.append = function (str) {
		this.strings.push(str);
	};

	module.StringBuffer.prototype.toString = function () {
		return this.strings.join("");
	};
	return module;
});